package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/jsp/cart/Cart.jsp";
    private static final String ERROR = "/jsp/common/Error.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CartService cartService = new CartService();
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if (session.getAttribute("account") == null) {
            session.setAttribute("message", "Please Sign In At First!");
            request.getRequestDispatcher(ERROR).forward(request, response);
        } else {

            Account account = (Account) session.getAttribute("account");
            cart = cartService.getCartByUserId(account.getUsername());
            if (cart == null) {
                cart = new Cart();
                session.setAttribute("cart", cart);
            }
            if (account != null) {
                HttpServletRequest httpRequest = request;
                String strBackUrl = "https://" + request.getServerName() + ":" + request.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " view shopping cart " + cart;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            request.getRequestDispatcher(VIEW_CART).forward(request, response);
        }
    }
}
